package test.linkedlistsplitter;

public class ListNode1 {
    int val;
    ListNode1 next;

    ListNode1(int x) {
        val = x;
    }

    public static void main(String[] args) {
        ListNode1 root = null, last = null;
        for (int i = 0; i < 0; i++) {
            ListNode1 node = new ListNode1(i + 1);
            if (i == 0) {
                root = node;
                last = node;
            } else {
                last.next = node;
                last = last.next;
            }
        }
        ListNode1[] ListNode1s = new ListNode1(0).new Solution().splitListToParts(root, 5);
        System.out.println(ListNode1s);
    }

    class Solution {
        public ListNode1[] splitListToParts(ListNode1 root, int k) {
            ListNode1 cur = root;
            int N = 0;
            while (cur != null) {
                cur = cur.next;
                N++;
            }

            int width = N / k, rem = N % k;

            ListNode1[] ans = new ListNode1[k];
            cur = root;
            for (int i = 0; i < k; ++i) {
                ListNode1 head = cur;
                for (int j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) {
                    if (cur != null) cur = cur.next;
                }
                if (cur != null) {
                    ListNode1 prev = cur;
                    cur = cur.next;
                    prev.next = null;
                }
                ans[i] = head;
            }
            return ans;
        }
    }


}
